﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serializer
{
    public class SerializeBinary
    {
        public static MemoryStream SerializeBinaryToMemoryStream(object o)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, o);

            return ms;
        }

        public static byte[] ObjectToByte(object o)
        {
            MemoryStream ms = SerializeBinary.SerializeBinaryToMemoryStream(o);
            return ms.ToArray();
        }

        public static T DeSerializeBinaryFromMemoryStream<T>(MemoryStream ms)
        {
            BinaryFormatter bf = new BinaryFormatter();
            object o = bf.Deserialize(ms);
            ms.Close();
            return (T)o;
        }

        public static T BtyeToObject<T>(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer);
            return SerializeBinary.DeSerializeBinaryFromMemoryStream<T>(ms);
        }

    }
}
